package org.yuanqiframework.yuanqi.web.utils;

import org.springframework.boot.system.ApplicationHome;
import org.springframework.context.ResourceLoaderAware;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Component;
import org.springframework.util.FileCopyUtils;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;

/**
 * @description: spring资源加载工具
 * @author: 曹波涛
 * @create: 2025/4/23
 **/
@Component
public class ResourceUtils implements ResourceLoaderAware {

    private static final String CLASSPATH_URL_PREFIX = "classpath:";
    private static final String FILE_URL_PREFIX = "file:";
    private static ResourceLoader loader;
    private static ApplicationHome applicationHome;

    @Override
    public void setResourceLoader(ResourceLoader resourceLoader) {
        loader = resourceLoader;
        applicationHome = new ApplicationHome();
    }

    @Deprecated
    public static Resource getClasspathResource(String fileName) {
        return loader.getResource(CLASSPATH_URL_PREFIX + fileName);
    }

    @Deprecated
    public static InputStream getClasspathResourceAsStream(String fileName) throws IOException {
        return loader.getResource(CLASSPATH_URL_PREFIX + fileName).getInputStream();
    }

    public static String readFileFromResourcesFolder(String fileName) throws IOException {
        try (InputStream inputStream = new ClassPathResource(fileName).getInputStream()) {
            byte[] bData = FileCopyUtils.copyToByteArray(inputStream);
            return new String(bData, StandardCharsets.UTF_8);
        }
    }

    //文件系统路径（file:）
    public static Resource getFileSystemResource(String fileName) {
        return loader.getResource(FILE_URL_PREFIX + fileName);
    }

    public static InputStream getFileSystemResourceAsStream(String fileName) throws IOException {
        return loader.getResource(FILE_URL_PREFIX + fileName).getInputStream();
    }

    public static Resource getApplicationHomeResource(String fileName) {
        return loader.getResource(FILE_URL_PREFIX + applicationHome.getDir().getAbsolutePath() + File.separator + fileName);
    }

    public static InputStream getApplicationHomeResourceAsStream(String fileName) throws IOException {
        return loader.getResource(FILE_URL_PREFIX + applicationHome.getDir().getAbsolutePath() + File.separator + fileName).getInputStream();
    }


}
